var validator;
var $studentAddForm = $("#student-add-form");
var username = $('#user_name').text();

function initVisitUsername() {
    $('#username').val(username);
}
$(function() {
    validateRule();
    initVisitUsername();

    $("#student-add .btn-save").click(function() {
        var name = $(this).attr("name");
        var validator = $studentAddForm.validate();
        var flag = validator.form();
        if (flag) {
            if (name == "save") {
                $.post(ctx + "visitStudent/add", $studentAddForm.serialize(), function(r) {
                    if (r.code == 0) {
                        closeModal();
                        $MB.n_success(r.msg);
                        $MB.refreshTable("studentTable");
                    } else $MB.n_danger(r.msg);
                });
            }
            if (name == "update") {
                $.post(ctx + "visitStudent/update", $studentAddForm.serialize(), function(r) {
                    if (r.code == 0) {
                        closeModal();
                        $MB.n_success(r.msg);
                        $MB.refreshTable("studentTable");
                    } else $MB.n_danger(r.msg);
                });
            }
        }
    });

    $("#student-add .btn-close").click(function() {
        closeModal();
    });

});

function closeModal() {
    $("#student-add-button").attr("name", "save");
    validator.resetForm();
    $MB.closeAndRestModal("student-add");
    $studentAddForm.find("input[name='studentname']").removeAttr("readonly");
    $("#student-add-modal-title").html('新增来校师生信息');
    $studentAddForm.find("input[name='status']").prop("checked",true);
}

function validateRule() {
    var icon = "<i class='zmdi zmdi-close-circle zmdi-hc-fw'></i> ";
    validator = $studentAddForm.validate({
        rules: {

            name: {
                required: true
            },
            graduate_high: {
                required: true
            },
            status: {
                required: true
            },
            telephone: {
                required: true,
                checkPhone: true
            }
        },
        errorPlacement: function(error, element) {
            if (element.is(":checkbox") || element.is(":radio")) {
                error.appendTo(element.parent().parent());
            } else {
                error.insertAfter(element);
            }
        },
        messages: {
            telephone: {
                required: icon + "请输入手机号",
                checkPhone: icon + "请输入正确的手机号"
            },
            name: icon + "请输入姓名",
            graduate_high: icon + "请输入毕业高中",
            status: icon + "请选择老师/学生"
        }
    });
}

